package ynu.edu.controller;

import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.*;
import ynu.edu.entity.Cart;
import ynu.edu.entity.CommonResult;
import ynu.edu.entity.User;
import ynu.edu.feign.ServiceProviderService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/userinfo")
public class CartController {
    @Resource
    private ServiceProviderService serviceInstance;

//    @CircuitBreaker(name = "backendA", fallbackMethod = "getCartByIdDown")
//    @Bulkhead(name = "bulkhead1", type = Bulkhead.Type.THREADPOOL, fallbackMethod = "getCartByIdDownForBulkhead")
    @GetMapping("/getCartById/{userId}")
    @LoadBalanced
//    @Bulkhead(name = "bulkheadThread1", type = Bulkhead.Type.THREADPOOL, fallbackMethod = "getCartByIdDownForThreadBulkhead")
    public CompletableFuture<CommonResult<Cart>> getCartById(@PathVariable("userId") Integer userId) {
        return CompletableFuture.supplyAsync(() -> {
            CommonResult<Cart> result = new CommonResult<>();
            Integer code = 200;
            String message = "success";
            Cart cart = new Cart();
            List<String> goods = new ArrayList<>();
            goods.add("玩具车");
            goods.add("笔记本电脑");
            cart.setGoodList(goods);
            User u = serviceInstance.getUserById(userId); // 假设这是你的服务方法
            cart.setUser(u);
            result.setResult(cart);
            result.setCode(code);
            result.setMsg(message);
            return result;
        });
    }

//    @CircuitBreaker(name = "backendB", fallbackMethod = "updateUserDown")
    @PutMapping("/updateUser")
    @LoadBalanced
    @RateLimiter(name = "rate1", fallbackMethod = "updateUserDownForRate")
    public String updateUser(@RequestBody User user) {
        serviceInstance.updateUser(user);
        return "更新用户信息成功!";
    }

    @PostMapping("/createUser")
    public User createUser(@RequestBody User user) {
        return serviceInstance.createUser(user);
    }

    @DeleteMapping("/deleteUser/{userId}")
    public String deleteUser(@PathVariable("userId") Integer userId) {
        serviceInstance.deleteUser(userId);
        return "User with ID " + userId + " deleted.";
    }

    public CompletableFuture<CommonResult<Cart>> getCartByIdDownForBulkhead(Integer userId, Exception e) {
//        e.printStackTrace();
        String errorMessage = "您好" + userId + "！您获取购物车信息的服务因并发限制已拒绝服务，请稍后再试！";
        Integer code = 501;
        CommonResult<Cart> result = new CommonResult<>();
        result.setResult(new Cart());
        result.setCode(code);
        result.setMsg(errorMessage);
        return CompletableFuture.completedFuture(result);
    }

    public CompletableFuture<CommonResult<Cart>> getCartByIdDownForThreadBulkhead(Integer userId, Exception e) {
        String errorMessage = "您好" + userId + "！您获取购物车信息的服务，因线程池和队列已满已拒绝服务，请稍后再试！";
        Integer code = 503;
        CommonResult<Cart> result = new CommonResult<>();
        result.setResult(new Cart());
        result.setCode(code);
        result.setMsg(errorMessage);
        return CompletableFuture.completedFuture(result);
    }

    public CompletableFuture<CommonResult<Cart>> getCartByIdDownForRate(Integer userId, Exception e) {
//        e.printStackTrace();
        String errorMessage = "您好" + userId + "！您获取购物车信息的服务已被限流，请稍后再试！";
        Integer code = 502;
        CommonResult<Cart> result = new CommonResult<>();
        result.setResult(new Cart());
        result.setCode(code);
        result.setMsg(errorMessage);
        return CompletableFuture.completedFuture(result);
    }

    public String updateUserDownForRate(User user, Exception e) {
        String errorMessage = "您好！您更新用户信息的服务已被限流，请稍后再试！";
        return errorMessage;
    }

    public String updateUserDown(User user, Exception e) {
        e.printStackTrace();
        return "更新用户信息失败，请稍后再试!";
    }
}
